import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useModel } from "umi";
import './index.less';
import { CpasIcon } from "~/public/cpas-ui";
import { Checkbox, Form, Row, Select } from 'antd';
import DataGrid, { Paging, Item, Column, Toolbar } from "devextreme-react/data-grid";
import { Button } from 'devextreme-react/button';
import { LoadIndicator } from 'devextreme-react/load-indicator';
import { getPeriodInfo, getReportList, updateReport_setting_column } from './service';
import moment from "moment";
import notify from "devextreme/ui/notify";
// import { moneyFormat } from "@/utils";

const { Option } = Select;

const BatchSettings = (props: any) => {
    const { initialState } = useModel('@@initialState');
    const { dbname, zcbfid, zcbfName } = initialState?.curPart as API.CurPart;
    // const [directionForm1] = Form.useForm();
    // const [directionForm] = Form.useForm();

    const eventsSaveData = useRef<any>([]);
    const DataGridRef = useRef<any>();
    const DataGridRef1 = useRef<any>();
    const [devLeftData, setDevLeftData] = useState<any[]>([]);
    const [devRightData, setDevRightData] = useState<any[]>([]);

    const [syncHomeBtn, setSyncHomeBtn] = useState<any>({
        loadIndicatorVisible: false,
        buttonText: '重算'
    });

    // const selectWidth = 120;
    const gtypes = [
        { value: '靠左对齐', label: '靠左对齐', itemkey: '1' },
        { value: '居中对齐', label: '居中对齐', itemkey: '2' },
        { value: '靠右对齐', label: '靠右对齐', itemkey: '3' },
        { value: '两端对齐', label: '两端对齐', itemkey: '4' },
    ];
    const gtypesData = [
        { value: '默认处理', label: '默认处理', itemkey: '1' },
        { value: '自动换行', label: '自动换行', itemkey: '2' },
        { value: '缩小字体', label: '缩小字体', itemkey: '3' },
        { value: '截断展示', label: '截断展示', itemkey: '4' },
    ];
    // const reverseOrder = [
    //     { value: '1', label: '是', itemkey: '1' },
    //     { value: '0', label: '否', itemkey: '2' },
    // ];
    // const onFinishSave1 = async () => {
    //     await directionForm1.validateFields();
    //     let formValues1 = directionForm1.getFieldsValue(); // 获取表单数据
    //     console.log("@@@ 表单数据1:", formValues1);
    // };


    const getReportData = async () => {
        const res = await getReportList({ dbname, isDesc: false });
        if (res.success) {
            eventsSaveData.current = [];
            // const formatString = "YYYY.MM.DD";
            const leftData = res.data.filter((item: { reportType: number, reportDate: any, title: any }) => {
                return item.reportType === 0;
            });
            const rightData = res.data.filter((item: { reportType: number }) => {
                return item.reportType === 1;
            });
            setDevLeftData(leftData);
            setDevRightData(rightData);
        }

    }


    const syncHomeYearList = async () => {
        setSyncHomeBtn({
            loadIndicatorVisible: true,
            buttonText: '重算中...'
        });
        const res = await getPeriodInfo({ dbname });
        if (res.success) {
            getReportData();
            notify(`获取首页年度数据成功！`, "success", 2000);
        } else {
            notify(`获取首页年度数据失败！`, "error", 2000);
        }

        setTimeout(() => {
            setSyncHomeBtn({
                loadIndicatorVisible: false,
                buttonText: '重算'
            });
        }, 500);
    }


    const changeSaveData = (newData: any) => {
        const tempID = newData.id;
        const resFind = eventsSaveData.current.find((item: any) => item.id === tempID);
        if (resFind) {
            // 修改更改的值
            eventsSaveData.current = eventsSaveData.current.map((item: { id: string; }) => {
                if (item.id === tempID) {
                    return newData;
                }
                return item;
            });
        } else {
            eventsSaveData.current.push(newData);
        }
    }

    const SavedData = (e: any) => {
        if (e.changes.length) {
            const { data } = e.changes[0];
            changeSaveData(data);
        }
    }

    const onFinishSave = () => {
        // await directionForm.validateFields();
        // let formValues = directionForm.getFieldsValue(); // 获取表单数据
        // console.log("@@@ 表单", formValues);
        if (eventsSaveData.current.length === 0) return;
        DataGridRef.current.instance.saveEditData().then(() => {
            DataGridRef1.current.instance.saveEditData().then(() => {
                const leftData = devLeftData.filter((item: { hide: boolean }) => {
                    return !item.hide;
                });
                const rightData = devRightData.filter((item: { hide: boolean }) => {
                    return !item.hide;
                });
                if (leftData.length === 0) return notify(`时点描述至少显示一行数据`, "warning", 2000);
                if (rightData.length === 0) return notify(`期间描述至少显示一行数据`, "warning", 2000);

                console.log(eventsSaveData.current, '@@@ 保存的数据');
                updateReport_setting_column(dbname, eventsSaveData.current).then((res: any) => {
                    if (res.success) {
                        getReportData();
                        notify(`修改数据成功！`, "success", 2000);
                        eventsSaveData.current = [];
                    } else {
                        notify(`修改数据失败！${res.data}`, "error", 2000);
                    }
                });

            });
        });
    };
    useEffect(() => {
        getReportData();
    }, []);

    return <>
        <div className="BatchSettingsStyle">
            <div>
                <p className="displayFlex">
                    <div>
                        一、表格审计期间配置
                        <span style={{ marginLeft: '16px', cursor: 'pointer' }}> <CpasIcon type='icon-baocun' fontSize={16} onClick={onFinishSave} /> </span>
                    </div>
                    <div>
                        <Button
                            type='default'
                            className="defaultBtn syncdefaultBtn"
                            width={110}
                            disabled={syncHomeBtn.loadIndicatorVisible}
                            onClick={() => {
                                syncHomeYearList();
                            }}
                        >
                            <LoadIndicator className="button-indicator" visible={syncHomeBtn.loadIndicatorVisible} />
                            <span className="dx-button-text">{syncHomeBtn.buttonText}</span>
                        </Button>
                        <Button
                            className="defaultReloadBtnWhite"
                            render={() => (<CpasIcon type='icon-refresh' fontSize={16} />)}
                            onClick={() => {
                                // let testObJ = { dbNameData: dbname, dbnameTest: "这是测试" };
                                // // 本地存储 持久化数据
                                // window.localStorage.setItem(`dbNameData-${dbname}`, JSON.stringify(testObJ));
                                getReportData();
                            }}
                        />
                    </div>

                </p>
                {/* <Form
                    form={directionForm}
                    onFinish={onFinishSave}
                    // initialValues={{ layout: 'inline' }} labelInValue={true}
                    size="small"
                    layout="horizontal"
                >
                    <div style={{ marginLeft: '20px' }}>
                        <Row style={{ height: 45 }}>
                            <Form.Item rules={[{ required: true, message: "是否期间逆序必填" }]} name="isOrder" label="是否期间逆序" >
                                
                                <Select style={{ width: selectWidth }} placeholder="请选择">
                                    {reverseOrder.map((item) =>
                                        <Option key={item.itemkey} label={item.label} value={item.value}>{item.label}</Option>
                                    )}
                                </Select>
                            </Form.Item>
                        </Row>

                    </div>
                </Form> */}
                <div style={{ display: 'flex' }}>
                    <div style={{ marginRight: 100 }}>
                        {useMemo(() => {
                            return <DataGrid
                                width={450}
                                height={310}
                                className="devHeadersCenter PaperDevSortableGrid"
                                keyExpr="id"
                                dataSource={devLeftData}
                                allowColumnReordering={true}
                                allowColumnResizing={true}
                                allowHeaderFiltering={false}
                                showBorders={true}
                                showRowLines={true}
                                ref={DataGridRef}
                                selection={{ mode: 'single' }}
                                columnResizingMode="widget"
                                columnMinWidth={70}
                                onSaved={SavedData}
                                editing={{
                                    mode: 'cell',
                                    allowUpdating: true,
                                    allowAdding: false,
                                    startEditAction: 'click',
                                    allowDeleting: false
                                }}

                            >
                                <Paging enabled={false} />
                                <Toolbar>
                                    <Item
                                        location='before'
                                        render={() => {
                                            return <span>时点描述</span>
                                        }}
                                    />
                                </Toolbar>
                                <Column
                                    caption={'期间'}
                                    dataField="reportDate"
                                    alignment='center'
                                    allowEditing={false}
                                    allowResizing={true}
                                    allowHeaderFiltering={false}
                                    width={140}
                                />
                                <Column
                                    caption={'描述'}
                                    dataField="title"
                                    alignment='center'
                                    allowResizing={true}
                                    allowHeaderFiltering={false}
                                />
                                <Column
                                    caption={'隐藏'}
                                    allowEditing={false}
                                    alignment='center'
                                    width={70}
                                    fixed={true}
                                    fixedPosition='right'
                                    cellRender={(record) => {
                                        const { data } = record;
                                        return (
                                            <Checkbox
                                                defaultChecked={data.hide}
                                                key={data.id}
                                                disabled={data.fieldName !== 'QC' && data.fieldName !== 'SQQM'}
                                                onChange={() => {
                                                    const changeData = { ...data, hide: !data.hide };
                                                    let changeTempObj: any = {}
                                                    if (data.fieldName === 'QC') {
                                                        const temmFilter = devLeftData.filter((item: any) => item.fieldName === 'SQQM');
                                                        changeTempObj = { ...temmFilter[0], hide: data.hide }
                                                    }

                                                    if (data.fieldName === 'SQQM') {
                                                        const temmFilter = devLeftData.filter((item: any) => item.fieldName === 'QC');
                                                        changeTempObj = { ...temmFilter[0], hide: data.hide }
                                                    }
                                                    setDevLeftData((oldData: any) => {
                                                        let newData = [...oldData];
                                                        newData = newData.map((item: any) => {
                                                            if (item.id === changeData.id) {
                                                                changeSaveData(changeData);
                                                                return changeData;
                                                            }
                                                            if (item.id === changeTempObj.id) {
                                                                changeSaveData(changeTempObj);
                                                                return changeTempObj
                                                            }
                                                            return item;
                                                        });
                                                        return newData;
                                                    });
                                                    return data.hide = !data.hide;
                                                }}
                                            />
                                        )
                                    }}
                                />
                            </DataGrid >
                        }, [devLeftData])}
                    </div>
                    <div>
                        {useMemo(() => {
                            return <DataGrid
                                width={450}
                                height={310}
                                className="devHeadersCenter PaperDevSortableGrid"
                                keyExpr="id"
                                dataSource={devRightData}
                                allowColumnReordering={true}
                                allowColumnResizing={true}
                                allowHeaderFiltering={false}
                                showBorders={true}
                                showRowLines={true}
                                ref={DataGridRef1}
                                selection={{ mode: 'single' }}
                                columnResizingMode="widget"
                                columnMinWidth={70}
                                onSaved={SavedData}
                                editing={{
                                    mode: 'cell',
                                    allowUpdating: true,
                                    allowAdding: false,
                                    startEditAction: 'click',
                                    allowDeleting: false
                                }}
                            >
                                <Paging enabled={false} />
                                <Toolbar>
                                    <Item
                                        location='before'
                                        render={() => {
                                            return <span>期间描述</span>
                                        }}
                                    />
                                </Toolbar>
                                <Column
                                    caption={'期间'}
                                    dataField="reportDate"
                                    alignment='center'
                                    allowEditing={false}
                                    allowResizing={true}
                                    allowHeaderFiltering={false}
                                    width={110}
                                />
                                <Column
                                    caption={'描述'}
                                    dataField="title"
                                    alignment='center'
                                    allowResizing={true}
                                    allowHeaderFiltering={false}
                                />
                                {/*    <Column
                                    caption={'隐藏'}
                                    alignment='center'
                                    width={70}
                                    fixed={true}
                                    fixedPosition='right'
                                    cellRender={(record) => {
                                        const { data } = record;
                                        return (
                                            <Checkbox
                                                defaultChecked={data.hide}
                                                key={data.id}
                                                onChange={() => {
                                                    const changeData = { ...data, hide: !data.hide };
                                                    setDevRightData((oldData: any) => {
                                                        let newData = [...oldData];
                                                        newData = newData.map((item: any) => {
                                                            if (item.id === changeData.id) {
                                                                return changeData;
                                                            }
                                                            return item;
                                                        });
                                                        return newData;
                                                    });
                                                    changeSaveData(changeData);
                                                    return data.hide = !data.hide
                                                }}
                                            />
                                        )
                                    }}
                                /> */}
                            </DataGrid >
                        }, [devRightData])}
                    </div>
                </div>
            </div>
            {/* <div>
                <p>
                    二、表格样式设置
                    <span style={{ marginLeft: '16px' }}> <CpasIcon type='icon-baocun' fontSize={16} onClick={onFinishSave} /> </span>
                </p>
                <div>
                    <Form
                        form={directionForm}
                        onFinish={onFinishSave}
                        size="small"
                        layout="horizontal"
                    >
                        <div>
                            <b>表头编辑</b>
                        </div>
                        <div style={{ marginLeft: '20px' }}>
                            <Row style={{ height: 45 }}>
                                <Form.Item rules={[{ required: true, message: "对齐方式必填" }]} name="username1" label="表头第一行对齐方式" >
                                    <Select style={{ width: selectWidth }} placeholder="请选择">
                                        {gtypes.map((item) =>
                                            <Option key={item.itemkey} label={item.label} value={item.value}>{item.label}</Option>
                                        )}
                                    </Select>
                                </Form.Item>
                            </Row>
                            <Row style={{ height: 45 }}>
                                <div style={{ display: 'flex' }}>
                                    <Form.Item style={{ marginRight: 15 }} rules={[{ required: true, message: "项目列必填" }]} name="username2" label="表头非第一行对齐方式：项目列" >
                                        <Select style={{ width: selectWidth }} placeholder="请选择">
                                            {gtypes.map((item) =>
                                                <Option key={item.itemkey} label={item.label} value={item.value}>{item.label}</Option>
                                            )}
                                        </Select>
                                    </Form.Item>
                                    <Form.Item style={{ marginRight: 15 }} rules={[{ required: true, message: "文本列必填" }]} name="username3" label="文本列" >
                                        <Select style={{ width: selectWidth }} placeholder="请选择">
                                            {gtypes.map((item) =>
                                                <Option key={item.itemkey} label={item.label} value={item.value}>{item.label}</Option>
                                            )}
                                        </Select>
                                    </Form.Item>
                                    <Form.Item style={{ marginRight: 15 }} rules={[{ required: true, message: "数字列必填" }]} name="username4" label="数字列" >
                                        <Select style={{ width: selectWidth }} placeholder="请选择">
                                            {gtypes.map((item) =>
                                                <Option key={item.itemkey} label={item.label} value={item.value}>{item.label}</Option>
                                            )}
                                        </Select>
                                    </Form.Item>
                                    <Form.Item style={{ marginRight: 15 }} rules={[{ required: true, message: "百分比必填" }]} name="username5" label="百分比" >
                                        <Select style={{ width: selectWidth }} placeholder="请选择">
                                            {gtypes.map((item) =>
                                                <Option key={item.itemkey} label={item.label} value={item.value}>{item.label}</Option>
                                            )}
                                        </Select>
                                    </Form.Item>
                                </div>
                            </Row>
                            <Row style={{ height: 45 }}>
                                <Form.Item rules={[{ required: true, message: "超长处理方式必填" }]} name="username6" label="表头超长处理" >
                                    <Select style={{ width: selectWidth }} placeholder="请选择">
                                        {gtypesData.map((item) =>
                                            <Option key={item.itemkey} label={item.label} value={item.value}>{item.label}</Option>
                                        )}
                                    </Select>
                                </Form.Item>
                            </Row>
                        </div>
                        <div>
                            <b>表体编辑</b>
                        </div>
                        <div style={{ marginLeft: '20px' }}>
                            <Row style={{ height: 45 }}>
                                <div style={{ display: 'flex' }}>
                                    <Form.Item style={{ marginRight: 15 }} rules={[{ required: true, message: "超长处理方式必填" }]} name="username7" label="文本超长处理" >
                                        <Select style={{ width: selectWidth }} placeholder="请选择">
                                            {gtypesData.map((item) =>
                                                <Option key={item.itemkey} label={item.label} value={item.value}>{item.label}</Option>
                                            )}
                                        </Select>
                                    </Form.Item>
                                    <Form.Item style={{ marginRight: 15 }} rules={[{ required: true, message: "超长处理方式必填" }]} name="username8" label="数字超长处理" >
                                        <Select style={{ width: selectWidth }} placeholder="请选择">
                                            {gtypesData.map((item) =>
                                                <Option key={item.itemkey} label={item.label} value={item.value}>{item.label}</Option>
                                            )}
                                        </Select>
                                    </Form.Item>
                                    <Form.Item style={{ marginRight: 15 }} rules={[{ required: true, message: "超长处理方式必填" }]} name="username9" label="百分比超长处理" >
                                        <Select style={{ width: selectWidth }} placeholder="请选择">
                                            {gtypesData.map((item) =>
                                                <Option key={item.itemkey} label={item.label} value={item.value}>{item.label}</Option>
                                            )}
                                        </Select>
                                    </Form.Item>
                                </div>
                            </Row>
                        </div>

                    </Form>
                </div>

            </div> */}
        </div>
    </>
}
export default BatchSettings;
